package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.OtherRobotAdmin;
import com.ruoyi.system.domain.RobotWechatUser;
import com.ruoyi.system.domain.vo.BindTypeEnum;
import com.ruoyi.system.mapper.RobotWechatUserMapper;
import com.ruoyi.system.service.IRobotWechatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.List;


/**
 * 机器人微信用户业务
 */
@Service
public class RobotWechatUserServiceImpl extends ServiceImpl<RobotWechatUserMapper, RobotWechatUser> implements IRobotWechatUserService {

    @Autowired
    OtherRobotAdminServiceImpl otherRobotAdminServiceImpl;

    /**
     * 机器人appid
     */
    @Value(value = "${robot.appid}")
    private String appid;

    /**
     * 机器人app secert
     */
    @Value(value = "${robot.appserect}")
    private String appsecert;

    /**
     * 小程序登录流程//用于判断是否可以跳转到页面
     * <p>
     * 1 获取用户openid
     * 2 通过openid 绑定口令 通过口令去查机器人后台用户是否绑定
     * 3 返回是否绑定状态
     */
    public RobotWechatUser wechatLogin(String code) {

        log.error("code"+code);

        //获取openid
        String openidByCode = "";
        try {
            openidByCode = getOpenidByCode(code);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //查询是否有记录
        RobotWechatUser wechatUser = getOne(new LambdaQueryWrapper<RobotWechatUser>().eq(RobotWechatUser::getOpenid, openidByCode));
        if (null == wechatUser) {
            return createRobotWechatUser(openidByCode);
        } else {
            if (null != wechatUser.getBinding() && wechatUser.getBinding().equals(BindTypeEnum.BINDING_OK.getCode())) {
                //说明绑定了
                return wechatUser;
            } else {
                //说明没有绑定
                //查询机器人后台接口http 使用口令查询
                if (checkUserBindFormRobot(wechatUser.getPasswordCommand())) {
                    wechatUser.setBinding(BindTypeEnum.BINDING_OK.getCode());
                    updateById(wechatUser);
                } else {
//                    wechatUser.setPasswordCommand(BindTypeEnum.NO_BANDING.getCode());
//                    updateById(wechatUser);
                }
            }
            return wechatUser;
        }
    }


    /**
     * 获取口令 口令是永久的不会变化的，每个人口令不一样
     *
     * @return
     */
    @Transactional(isolation = Isolation.SERIALIZABLE)
    public RobotWechatUser getUserPasswordCommand(String openid) {
        RobotWechatUser wechatUser = getOne(new LambdaQueryWrapper<RobotWechatUser>().eq(RobotWechatUser::getOpenid, openid));
        if (null == wechatUser) {
            RobotWechatUser robotWechatUser = new RobotWechatUser();
            robotWechatUser.setOpenid(openid);
            robotWechatUser.setPasswordCommand(createPasswordCommand());
            save(robotWechatUser);
            return robotWechatUser;
        } else {
            if (wechatUser.getPasswordCommand() == null || wechatUser.getPasswordCommand().isEmpty()) {
                wechatUser.setPasswordCommand(createPasswordCommand());
                updateById(wechatUser);
            }
            return wechatUser;
        }
    }

    /**
     * 判断用户是否绑定
     *
     * @param openid
     * @return
     */
    public Boolean checkUserBinding(String openid) {
        RobotWechatUser wechatUser = getOne(new LambdaQueryWrapper<RobotWechatUser>().eq(RobotWechatUser::getOpenid, openid));
        if (null == wechatUser) {
            return false;
        }
        return wechatUser.getBinding().equals(BindTypeEnum.BINDING_OK.getCode());
    }

    /**
     * 调用http接口判断用户是否绑定到robot上
     *
     * @param passwordCommand
     * @return
     */
    public Boolean checkUserBindFormRobot(String passwordCommand) {
        List<OtherRobotAdmin> otherRobotAdmin = otherRobotAdminServiceImpl.getOtherRobotAdmin(passwordCommand);

        return null != otherRobotAdmin && !otherRobotAdmin.isEmpty();
    }

    /**
     * 创建用户记录
     *
     * @param openidByCode
     * @return
     */

    public RobotWechatUser createRobotWechatUser(String openidByCode) {
        RobotWechatUser robotWechatUser = new RobotWechatUser();
        robotWechatUser.setOpenid(openidByCode);
        robotWechatUser.setPasswordCommand(createPasswordCommand());
        save(robotWechatUser);
        return robotWechatUser;
    }

    /**
     * 创建口令
     */
    public String createPasswordCommand() {
        //循环5次
        for (int i = 0; i < 5; i++) {
            String passwordCommand = generatePasswordCommand();
            RobotWechatUser robotWechatUser = getOne(new LambdaQueryWrapper<RobotWechatUser>().eq(RobotWechatUser::getPasswordCommand, passwordCommand));
            if (null == robotWechatUser) {
                return passwordCommand;
            }
        }
        return "";
    }

    /**
     * 生成位随机口令
     *
     * @return
     */
    private String generatePasswordCommand() {
        int length = 16;
        String characters = "ABCDEFGHIJKLMNOQRSTUVWXYZ0123456789";
        SecureRandom random = new SecureRandom();
        StringBuilder sb = new StringBuilder();
        sb.append("WORD_");
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }


    /**
     * 通过微信code获取 openId
     *
     * @param code
     * @return
     * @throws IOException
     */
    public String getOpenidByCode(String code) throws IOException {

        log.error(code);

        String APP_ID = appid;
        String APP_SECRET = appsecert;
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        // 解析 JSON 获取 OpenID
        log.error(response.toString());
        return parseOpenId(response.toString());
    }

    private static String parseOpenId(String jsonResponse) {
        // 简朴解析，通常使用 JSON 库解析

        return jsonResponse.split("\"openid\":\"")[1].split("\"")[0];
    }


/**
 * 后续业务流程
 */

}
